import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_demo/core/common/utils/image_utils.dart';
import 'package:flutter_demo/core/common/values/gaps.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:flutter_demo/core/typeof/function.dart';
import 'package:flutter_demo/ui/pages/search/mudule/answer_item.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

import 'index.dart';

class SearchPage extends GetView<SearchController> {
  static const String routeName = "/SearchPage";
  SearchPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SearchController>(
      builder: (_) {
        return Scaffold(
            //搜索框
            appBar: PreferredSize(
              preferredSize:
                  Size.fromHeight(44.h + context.mediaQueryPadding.top),
              child: Padding(
                padding: EdgeInsets.only(top: context.mediaQueryPadding.top),
                child: _buildSearch(context),
              ),
            ),
            //搜索结果
            body: SafeArea(
                child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(1),
                    ),
                    child: SmartRefresher(
                      controller: controller.refreshController,
                      enablePullUp: true,
                      onRefresh: () {
                        controller.onRefreshPage();
                      },
                      onLoading: () {
                        controller.onMorePage();
                      },
                      child: ListView.separated(
                        shrinkWrap: true,
                        scrollDirection: Axis.vertical,
                        // padding: EdgeInsets.only(left: 15.w, right: 15.w),
                        itemBuilder: (context, index) {
                          AnswerItem? answerList =
                              controller.state.vo?.answerList![index];
                          final list = <Widget>[];
                          list.add(
                              createCard(answerList?.question ?? "", false));
                          (answerList!.answers ?? []).forEach((element) {
                            list.add(Gaps.lineRigth20);
                            list.add(createCard(element, true));
                          });
                          return Column(
                            children: list,
                          );
                        },
                        separatorBuilder: (context, index) {
                          return Gaps.line20_3;
                        },
                        itemCount: controller.state.vo?.answerList?.length ?? 0,
                      ),
                    ))));
      },
    );
  }

  //搜索框
  Widget _buildSearch(BuildContext context) {
    return Container(
      color: Colors.black,
      child: Row(
        children: [
          //回退按钮
          GestureDetector(
            onTap: () {
              Get.back();
              controller.hideKeyboard();
            },
            behavior: HitTestBehavior.translucent,
            child: Container(
              height: 40.h,
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              alignment: Alignment.center,
              child: Image.asset(
                ImageUtils.getImagePath('dij'),
                color: Colors.white,
                height: 25.h,
              ),
            ),
          ),
          //搜索框
          Expanded(
            child: Container(
              height: 30.h,
              margin: EdgeInsets.only(right: 16.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(18.r),
                  color: Colors.blue.withOpacity(0.8)),
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 6.h),
              child: TextField(
                controller: controller.state.editingController,
                focusNode: controller.state.focusNode,
                style: const TextStyle()
                    .copyWith(fontWeight: FontWeight.normal, fontSize: 16.sp),
                decoration: InputDecoration(
                    isDense: true,
                    border: InputBorder.none,
                    //constraints: BoxConstraints(maxHeight: 18.h),
                    prefixIconConstraints:
                        BoxConstraints(minWidth: 26.w, maxHeight: 18.h),
                    prefixIcon: Image.asset(
                      ImageUtils.getImagePath('search'),
                      color: const Color.fromARGB(255, 155, 155, 155),
                    ),
                    hintStyle: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.normal),
                    hintText: controller.state.keywords),
                onEditingComplete: () {
                  controller
                      .onSearchPage(controller.state.editingController.text);
                  //logic.search(state.keywordsValue);
                },
                textInputAction: TextInputAction.search,
                onChanged: (word) {
                  //logic.searchSuggest(word);
                },
              ),
            ),
          ),

          //搜索按钮
          GestureDetector(
            onTap: () {
              // Get.back();
              controller.onSearchPage(controller.state.editingController.text);
            },
            behavior: HitTestBehavior.translucent,
            child: Container(
                height: 40.h,
                padding: EdgeInsets.symmetric(horizontal: 15.w),
                alignment: Alignment.center,
                child: Text(
                  "搜索",
                  style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.normal),
                )),
          ),
        ],
      ),
    );
  }
}

//搜索列表
Widget createCard(String text, bool copy) {
  return Container(
      height: 30.h,
      margin: EdgeInsets.only(left: 18.w, right: 18.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 0,
            child:
                //原型裁剪
                ClipOval(
              child: Container(
                alignment: Alignment.center,
                width: 25.w,
                height: 25.h,
                //背景颜色
                color: copy ? Colors.orange : Colors.blue,
                // .withOpacity(0.05),
                child: Image.asset(
                  ImageUtils.getImagePath("icn_account"),
                  color: Colors.white,
                  width: 18.w,
                  height: 18.h,
                ),
              ),
            ),
          ),
          Expanded(
              child: Padding(
            padding: EdgeInsets.only(left: 10.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                    width: 240.w,
                    child: Text(
                      breakWord(text),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )),
                copy
                    ? SizedBox(
                        height: 25.h,
                        child: elementButtonWidget("复制", onPressed: () {
                          Clipboard.setData(ClipboardData(text: text));
                        }),
                      )
                    : Gaps.empty
              ],
            ),
          ))
        ],
      ));
}

//解决隐藏长度问题
String breakWord(String word) {
  if (word == null || word.isEmpty) {
    return word;
  }
  String breakWord = ' ';
  word.runes.forEach((element) {
    breakWord += String.fromCharCode(element);
    breakWord += '\u200B';
  });
  return breakWord;
}

/**
 * 自定义通用按钮
 */
Widget elementButtonWidget(String? title, {ParamVoidCallback? onPressed}) {
  if (title == null) return Gaps.empty;
  final theme = Get.theme;
  return MaterialButton(
    onPressed: () {
      if (onPressed == null) {
        logger.i("通用按钮被点击了");
        //RouteUtils.routeFromActionStr(elementButton.action);
      } else {
        onPressed.call();
      }
    },

    height: 24.h,
    color: Colors.transparent,
    //按钮点击下的颜色
    highlightColor: theme.hintColor,

    //按钮的阴影
    elevation: 0,
    padding: const EdgeInsets.all(0),
    minWidth: 40.h,
    focusElevation: 0,

    ///按钮按下时的阴影高度
    highlightElevation: 0,

    ///用来设置按钮的边框的样式
    shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.r),
        side: BorderSide(
          color: Colors.blue,
        )),
    child: Row(children: [
      Gaps.hGap12,
      //标题前图片
      // Image.asset(ImageUtils.getImagePath('icon_play_small'),
      //     color: theme.iconTheme.color, width: 12.w, height: 12.h),
      Text(
        title.toString(),
        style: TextStyle(fontSize: 12.sp, color: Colors.blue),
      ),
      Gaps.hGap10,
    ]),
  );
}
